<?php
/**
-------------------------
GNU GPL COPYRIGHT NOTICES
-------------------------
This file is part of FlexicaCMS.

FlexicaCMS is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

FlexicaCMS is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with FlexicaCMS.  If not, see <http://www.gnu.org/licenses/>.*/

/**
 * $Id$
 *
 * @author FlexicaCMS team <contact@flexicacms.com>
 * @link http://www.flexicacms.com/
 * @copyright Copyright &copy; 2009-2010 Gia Han Online Solutions Ltd.
 * @license http://www.flexicacms.com/license.html
 */
class SiteService extends FServiceBase
{
    /**
    * Create a new post
    *
    * @param array
    */
    public function sendContact($params){
    	$contactForm = $this->getModel($params['ContactForm'], 'ContactForm');
		$this->result->processed('contactForm', $contactForm);
    	if(!$contactForm->validate())
    	{
			return $this->result->fail(0, 'Invalid data');
		}

    	$senderEmail = $this->getParam($params, 'senderEmail', '');

    	$headers="From: {$contactForm->email}\r\nReply-To: {$contactForm->email}";
		if(!mail($senderEmail,$contactForm->subject,$contactForm->body,$headers)) {
			return $this->result->fail(0, 'E-mail was not sent successfully');
		}
    }

    /**
    * Login
    *
    * @param array
    */
    public function login($params)
	{
		$loginForm = $this->getModel($params['LoginForm'], 'LoginForm');
		$this->result->processed('loginForm', $loginForm);
		if(!$loginForm->validate())
    	{
			return $this->result->fail(0, 'Invalid data');
		}

		$identity = new UserIdentity($loginForm->username,$loginForm->password);
		if(!$identity->authenticate()) {
			$loginForm->addError('password','Incorrect username or password.');
			return $this->result->fail(0, 'Incorrect username or password.');
		}

		if($identity->errorCode===UserIdentity::ERROR_NONE)
		{
			$duration=$loginForm->rememberMe ? 3600*24*30 : 0; // 30 days
			Yii::app()->user->login($identity,$duration);
		}
		else {
			$this->result->addError('LoginForm', 'Authentication failed');
		}
    }
    
    /**
        * This is used for upload image 
        * Move Image in tempateImage folder to a specific folder
        * @param mixed $params
        * @return FServiceModel
        */
        public function moveImageToMainFolder($params){
            $stringImages=array();
            $files=$this->getParam($params,"files",array());
            $id=$this->getParam($params,"id",0);
            if($id==0){
                return $this->result->fail(ERROR_INVALID_DATA, Yii::t('User.UserProfile','Invalid Image ID.')); 
            }
            $type=$this->getParam($params,"type",'');
            if($type==''){
                return $this->result->fail(ERROR_INVALID_DATA, Yii::t('User.UserProfile','Invalid type.')); 
            }
            $mainFolder = Yii::app()->params['ProfileFolder'];
            if(count($files)>0){
                //Get path folder in params config       
                $TmpImagesFolder = Yii::app()->params['TmpImagesFolder'];
                $basePath = Yii::getPathOfAlias("webroot").'/'.$TmpImagesFolder;
                if (is_dir($basePath))
                {
                    $dir = opendir($basePath);  
                    //List all file in folder TmpImagesFolder
                    while( ($entry = readdir($dir))!==false )
                    {
                        if( $entry[0]!=='.' )
                        { 
                            //If file is of this comment
                            if(in_array($entry,$files)){
                                $entryPath = $basePath.'/'.$entry;                        
                                $fileExt = end(explode('.',$entry));
                                $oldFileName=str_replace($fileExt,'',$entry);                                             
                                $oldFileName=trim($oldFileName,'.');
                                $newFileName = md5(time()).'_'.$oldFileName.'.'.$fileExt;                            
                                //Update model
                                $newFolder=Yii::getPathOfAlias("webroot").'/'.$mainFolder;
                                if(!is_dir($newFolder)){
                                    $r = mkdir($newFolder, 0777, true);
                                    if (! $r)
                                        throw new CHttpException(501, 'Could not create folder '.$newFolder);
                                }
                                if (copy($entryPath,$newFolder.''.$newFileName))
                                {    
                                    //delete image in folder temp                                
                                    $stringImages[]=$newFileName;
                                    unlink($entryPath);

                                    //remove file moved
                                    $key=array_search($entry,$files);
                                    unset($files[$key]);                                                                        
                                }                            
                            }                                                        
                        }                    

                    }                      

                }

            }
            $Images=array_merge($files,$stringImages);            
            $model=new $type; 
            $data=$model->findByPk($id);                                
            $data->avatar=implode(',',$Images);
            $data->save(false);
            return $this->result;    
        }
        public function deleteFileInTemp($params){
            $fileName=$this->getParam($params,'fileName','');            
            $location=$this->getParam($params,'location','');            
            if($fileName!=''){
                if(!$location){
                    $location = Yii::app()->params['TmpImagesFolder'];                
                }                                
                $basePath = Yii::getPathOfAlias("webroot").'/'.$location;
                if (is_dir($basePath))
                {
                    $dir = opendir($basePath);  
                    while( ($entry = readdir($dir))!==false )
                    {                           
                        if(($entry==$fileName)){
                            $filePath = $basePath.'/'.$fileName;                                
                            unlink($filePath);                                   
                        }
                    }                
                }
            }        
            return $this->result;
        }
}
?>